package com.orderplus.opshop.core.proxy;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;


public class TestProxyIp {


	public static String proxyGet(String href, String ip, String port) {
		try {
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, Integer.parseInt(port)));
			URL url = new URL(href);
			HttpsURLConnection urlcon = (HttpsURLConnection) url.openConnection(proxy);
			urlcon.connect();         //获取连接
			InputStream is = urlcon.getInputStream();
			BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
			StringBuffer bs = new StringBuffer();
			String l = null;
			while ((l = buffer.readLine()) != null) {
				bs.append(l);
			}
			System.out.println(bs.toString());
			return bs.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}


	/**
	 * GET请求
	 *
	 * @param url   请求的URL
	 * @param param 请求参数，name1=value1&name2=value2 的形式
	 * @return 响应结果
	 */
	public static String sendGet(String url, String param, boolean isproxy, String proxyHost, int proxyPort) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			if (param != null && !("".equals(param))) {
				urlNameString = url + "?" + param;
			}
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			HttpURLConnection connection = null;
			// 使用代理模式
			if (isproxy) {
				@SuppressWarnings("static-access")
				Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
				connection = (HttpURLConnection) realUrl.openConnection(proxy);
			} else {
				connection = (HttpURLConnection) realUrl.openConnection();
			}


			// 设置通用的请求属性
			for (Map.Entry<String, String> entry : setProperty().entrySet()) {
				connection.setRequestProperty(entry.getKey(), entry.getValue());
			}
			// 建立连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK
					|| connection.getResponseCode() == HttpURLConnection.HTTP_CREATED
					|| connection.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			} else {
				in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));
			}
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！");
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * POST请求
	 *
	 * @param url     发送请求的 URL
	 * @param param   请求参数 name1=value1&name2=value2 的形式
	 * @param isproxy 是否使用代理模式
	 * @return 响应结果
	 */
	public static String sendPost(String url, String param, boolean isproxy, String proxyHost, int proxyPort) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			HttpURLConnection conn = null;
			// 使用代理模式
			if (isproxy) {
				@SuppressWarnings("static-access")
				Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
				conn = (HttpURLConnection) realUrl.openConnection(proxy);
			} else {
				conn = (HttpURLConnection) realUrl.openConnection();
			}

//            // https
//            if (url.substring(0, 5).equals("https")) {
//                SSLContext ctx = MyX509TrustManagerUtils();
//                ((HttpsURLConnection) conn).setSSLSocketFactory(ctx.getSocketFactory());
//                ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
//                    //在握手期间，如果 URL 的主机名和服务器的标识主机名不匹配，则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。
//                    @Override
//                    public boolean verify(String arg0, SSLSession arg1) {
//                        return true;
//                    }
//                });
//            }

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// POST方法
			conn.setRequestMethod("POST");


			// 设置通用的请求属性
			for (Map.Entry<String, String> entry : setProperty().entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
			conn.connect();

			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			// 发送请求参数
			out.write(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK
					|| conn.getResponseCode() == HttpURLConnection.HTTP_CREATED
					|| conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			} else {
				in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
			}
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！");
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}


	//设置请求头属性
	public static Map<String, String> setProperty() {
		HashMap<String, String> pMap = new HashMap<String, String>();
		// pMap.put("Accept-Encoding", "gzip"); //请求定义gzip,响应也是压缩包
		pMap.put("connection", "Keep-Alive");
		pMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		pMap.put("Content-Type", "application/x-www-form-urlencoded");
		return pMap;
	}

	public static void getHtml(String str) {
		Document document = Jsoup.parse(str);
		System.out.println(document.html());
	}


	public static void main(String[] args) {
		try {
			ResultSet rs = SQLiteJDBC.SELECT("SELECT * FROM proxy_ip_list");
			while (rs.next()) {
				String ip = rs.getString("ip");
				String port = rs.getString("port");
				String uri = "https://accounts.douban.com/login";
				//getHtml(proxyGet(uri, ip, port));
				//getHtml(sendGet(uri,"", true, ip, Integer.parseInt(port)));
				getHtml(sendPost(uri, "", true, ip, Integer.parseInt(port)));
			}
			rs.close();
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
	}

}

